package cn.demo.text.editor.strategy.menu.action;

import javax.swing.*;
import java.awt.event.KeyAdapter;

import cn.demo.text.editor.constant.Str;
import java.awt.event.KeyEvent;

public class SearchAction implements Action {

    private String lastSearchTerm = "";
    private int lastIndex = -1;

    @Override
    public void operate(JTextArea jta) throws Exception {
        JPanel panel = new JPanel();
        JTextField searchField = new JTextField(lastSearchTerm, 50);
        JButton nextButton = new JButton(Str.NEXT);

        panel.add(new JLabel(Str.ENTER_TEXT_TO_SEARCH));
        panel.add(searchField);
        panel.add(nextButton);

        JDialog dialog = new JDialog();
        dialog.setTitle(Str.SEARCH);
        dialog.setModal(true);
        dialog.getContentPane().add(panel);
        dialog.pack();
        dialog.setLocationRelativeTo(null);

        // 定义搜索逻辑
        Runnable searchLogic = () -> {
            String searchTerm = searchField.getText();
            if (searchTerm != null && !searchTerm.isEmpty()) {
                if (!searchTerm.equals(lastSearchTerm)) {
                    lastSearchTerm = searchTerm;
                    lastIndex = -1;
                }
                searchAndHighlight(jta, searchTerm);
            }
        };

        // 为 "Next" 按钮添加事件监听
        nextButton.addActionListener(e -> searchLogic.run());

        // 为搜索字段添加回车键监听
        searchField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    searchLogic.run();
                }
            }
        });

        dialog.setVisible(true);
    }

    private void searchAndHighlight(JTextArea jta, String searchTerm) {
        String content = jta.getText();
        lastIndex = content.indexOf(searchTerm, lastIndex + 1);
        if (lastIndex != -1) {
            jta.setCaretPosition(lastIndex);
            jta.requestFocusInWindow();
            jta.select(lastIndex, lastIndex + searchTerm.length());
        } else {
            lastIndex = -1;
        }
    }
}